import json

from django.http import HttpResponse, JsonResponse

# Create your views here.
#前端接口 后台 -》  web    http://ip:8080/api/index？id=1212
from django.views import View
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from apitest.models import UserInfo, TestCaseModel
from apitest.serializers import UserInfoSerializer, TestCaseSerializer


def index(request):
  print(request.GET.get("id"))
  if request.method=='POST':
     if request.content_type=='application/json':
       body = json.loads(request.body.decode())
       print(body)
       #json
       userlist = list(UserInfo.objects.filter(name__contains=body.get('name')).values())
       return JsonResponse(userlist,safe=False)
  return HttpResponse('my name is view_class get')


def userlist(request,id):
   queryset= UserInfo.objects.filter(id=id)
   userlist = list(queryset.values())
   return JsonResponse(userlist,safe=False)

#面向对象  接口标准开发 resetfull
class UserInfoView(View):
  def get(self, request):
   return HttpResponse('my name is view_class get')

  def post(self,request):
    if request.content_type == 'application/json':
      body = json.loads(request.body.decode())
      print(body)
      #数据校验
      #查询数据库
      # json
      userlist = list(UserInfo.objects.filter(name__contains=body.get('name')).values())
      return JsonResponse(userlist, safe=False)
    #return HttpResponse('my name is view_class get')

#多了一个类 序列化类  6个接口全部自动生成 包括业务逻辑
class UserInfoViewDRF(ModelViewSet):
  serializer_class = UserInfoSerializer  # 序列号器
  queryset = UserInfo.objects.all()
  filterset_fields = ('name', 'age')  # 指定过滤的字段
  search_fields = ('name',)  # 支持模糊搜索
  ordering_fields = ("name", "age")  # 排序字段

  @action(methods=['get'], detail=False)
  def queryByNameAndId(self, request):
      query_name = request.query_params.get('name')
      age = request.query_params.get('age')
      obj = UserInfo.objects.filter(name=query_name, age=age)
      if (obj.exists()):
          ser = UserInfoSerializer(obj, many=True)
          return Response(ser.data, status=status.HTTP_200_OK)
      return Response({}, status=status.HTTP_200_OK)

  @action(methods=['get'], detail=True)
  def getdetail(self, request, pk):
      obj = UserInfo.objects.filter(name__contains=pk)
      if (obj.exists()):
          ser = UserInfoSerializer(obj, many=True)
          return Response(ser.data, status=status.HTTP_200_OK)
      return Response({}, status=status.HTTP_200_OK)

class TestCaseView(ModelViewSet):
    serializer_class = TestCaseSerializer
    queryset = TestCaseModel.objects.all()
    filterset_fields = ('name', 'age')  # 指定过滤的字段
    # search_fields = ('name', 'age')  # 支持模糊搜索
    # ordering_fields = ("name", 'age')  # 排序字段
